# coding=utf-8
# 代码文件：Academicplatform/com/dao/interaction_dao.py

"""交互管理 DAO"""
import pymysql
from com.dao.base_dao import BaseDao


class InteractionDao(BaseDao):
    def __init__(self):
        super().__init__()

    def findall(self):
        """查询所有交互"""

        interactions = []
        try:
            # 创建游标对象
            with self.conn.cursor() as cursor:
                # 执行 SQL 操作
                sql = 'select interactionid,userid1,userid2,startdate,overdate,status,points from interactions'
                cursor.execute(sql)
                # 提取结果集
                result_set = cursor.fetchall()

                for row in result_set:
                    interaction = {}
                    interaction['interactionid'] = row[0]
                    interaction['userid1'] = row[1]
                    interaction['userid2'] = row[2]
                    interaction['startdate'] = row[3]
                    interaction['overdate'] = row[4]
                    interaction['status'] = row[5]
                    interaction['points'] = row[6]
                    interactions.append(interaction)
                # with 代码块结束，关闭游标

        finally:
            # 关闭数据连接
            self.close()

        return interactions

    def create(self, interaction):
        """创建交互，插入到数据库"""

        try:
            # 创建游标对象
            with self.conn.cursor() as cursor:
                # 执行 SQL 操作
                sql = 'insert into interactions (interactionid,userid1,userid1,startdate,overdate,status,points) ' \
                        'values (%s,%s,%s,%s,%s,%s,%s)'
                affectedcount = cursor.execute(sql, interaction)
                print('成功插入{0}条数据'.format(affectedcount))
                # 提交数据库事务
                self.conn.commit()
                # with 代码块结束，关闭游标
        except pymysql.DatabaseError as e:
            # 回滚数据库事务
            self.conn.rollback()
            print(e)

        finally:
            # 关闭数据连接
            self.close()
